package lion.dev.thread;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * 长时间运行的线程进行控制
 *
 * <pre>
 * time   2013年9月17日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class ThreadFarm {

	private List<ThreadRunner> threads = new ArrayList<>();

	private String poolName;

	public ThreadFarm(int size, Runnable runnable) {

		this(size, runnable, false);
	}

	public ThreadFarm(int size, Runnable runnable, boolean daemon) {

		this(null, size, runnable, daemon);
	}

	public ThreadFarm(String poolName, int size,Runnable runnable, boolean daemon) {

		this.poolName = poolName;
		if (StringUtils.isBlank(this.poolName)) {
			this.poolName = "Thread";
		}
		for (int i = 0; i < size; i++) {
			ThreadRunner thread = new ThreadRunner(runnable);
			thread.setName(this.poolName + "-" + i);
			thread.setDaemon(daemon);
			threads.add(thread);
		}
	}

	/**
	 * 直接停止
	 */
	public void stop() {

		for (ThreadRunner rs : threads) {
			rs.shutdown();
		}
	}

	/**
	 * 等待全部停止
	 */
	public void awaitStop() {

		for (ThreadRunner rs : threads) {
			rs.shutdown();
		}
		for (ThreadRunner rs : threads) {
			try {
				rs.join();
			} catch (InterruptedException e) {
			}
		}
	}

	public void start() {

		for (ThreadRunner rs : threads) {
			rs.start();
		}
	}

}
